package cn.sczc.jh.client.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.sczc.jh.client.entity.Permission;
import cn.sczc.jh.client.entity.Role;
import cn.sczc.jh.client.entity.User;
import cn.sczc.jh.client.service.sys.UserService;
import cn.sczc.jh.client.util.WebUtil;

public class AuthRealm extends AuthorizingRealm {
	private UserService userService;

	public AuthRealm(UserService userService) {
		this.userService = userService;
	}

	/*
	 * 真实授权抽象方法，供子类调用
	 * 
	 * 这个是当登陆成功之后会被调用，看当前的登陆角色是有有权限来进行操作
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		// 获取登录用户名
		User user = (User) principals.getPrimaryPrincipal();
//		// 根据用户名去数据库查询用户信息
//		User user = userService.getUserByAccount(userName);
//		// 添加角色和权限
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		if (user.getRoles() != null) {
			for (Role role : user.getRoles()) {
				simpleAuthorizationInfo.addRole(role.getName());
			}
		}
		if (user.getPermissions() != null) {
			for (Permission per : user.getPermissions()) {
				simpleAuthorizationInfo.addStringPermission(per.getCode());
			}
		}
		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 加这一步的目的是在Post请求的时候会先进认证，然后在到请求
		if (token.getPrincipal() == null) {
			return null;
		}
		// 获取用户信息
		String username = token.getPrincipal().toString();
		User user = userService.getUserByAccount(username);
		if (user == null) {
			// 抛出 帐号找不到异常
			throw new UnknownAccountException();
		}
		// 这里验证authenticationToken和simpleAuthenticationInfo的信息
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),
				this.getClass().getName());

		WebUtil.saveCurrentUser(user.getId());
		WebUtil.saveCurrentUserName(user.getName());
		WebUtil.saveCurrentUserObj(user);
		return info;

	}

}
